<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form
          @submit.native.prevent
          label-width="100px"
          label-position="left"
        >
          <el-col :span="8">
            <el-form-item label="采购日期" style="height:30px">
               <el-date-picker
                v-model="datelist"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据编号">
              <el-input
                v-model="listQuery.fbillno"
                clearable
                class="filter-item"
                placeholder="请输入单据编号"
              />
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="8">
            <el-form-item label="单据状态">
              <el-select
                v-model="listQuery.fbillstate"
                class="filter-item"
                clearable
                placeholder="请选择单据状态"
              >
                <el-option
                  v-for="item in fbillstateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称">
              <el-select
                v-model="listQuery.fstockno"
                class="filter-item"
                placeholder="请选择仓库名称"
                clearable
              >
                <el-option
                  v-for="item in fstocknoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="searchOne" label="采购人员">
              <el-select
                style="display: inline-block"
                clearable
                filterable
                v-model="listQuery.forduser"
                class="filter-item"
                placeholder="请选择采购人员"
              >
                <el-option
                  v-for="item in getListforduser"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商">
              <el-select
                v-model="listQuery.fsupno"
                filterable
                clearable
                class="filter-item"
                placeholder="请选择供应商"
              >
                <el-option
                  v-for="item in getListfsupno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          </template>
          <el-col :span="8">
            <el-form-item>
              <el-button @click="handleFilter" type="primary">查找</el-button>
              <el-button @click="handleCreate" type="success">添加</el-button>
              <el-button @click="handleUpload" type="info">导入</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll=true"
                v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>
                收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <!-- 主表查询结果 -->
        <JNPF-table v-loading="listLoading" :data="list" @row-click="rowclick">
          <el-table-column
            align="center"
            label="操作"
            class-name="small-padding"
            :width="buttonColor.operationTwo"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.fbillstate === 1"
                @click="audit(scope.row)"
                >确认</el-button
              >
              <el-button type="text" v-else>确认</el-button>
              <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">作废</el-dropdown-item>
                <el-dropdown-item command="b">打印</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            </template>
          </el-table-column>
          <el-table-column
            :index="indexMethod"
            :width="buttonColor.line"
            align="center"
            label="序号"
            type="index"
          />
          <el-table-column
            align="left"
            label="单据编号"
            prop="fbillno"
            :width="buttonColor.billno"
          />
          <el-table-column
            :width="buttonColor.name"
            :formatter="formatfstockno"
            align="left"
            label="仓库名称"
            prop="fstockno"
          />
          <el-table-column
            :formatter="formatforduser"
            align="left"
            label="采购人员"
            prop="forduser"
            :width="buttonColor.user"
          />
          <el-table-column
            :formatter="datetimeFormat"
            align="left"
            label="实际到货"
            prop="frecdate"
            width="100"
          />
          <el-table-column
            :formatter="formatfsupno"
            align="left"
            label="供应商"
            prop="fsupno"
            :width="buttonColor.user"
          />
          <el-table-column align="left" label="备注" prop="fexplanation" />
          <el-table-column
            align="left"
            label="单据状态"
            :width="buttonColor.state"
            prop="fbillstate"
          >
            <template slot-scope="scope">
              <span
                :style="{ color: buttonColor.itemisconfirmed }"
                v-if="scope.row.fbillstate === 1"
                >{{ scope.row.fbillstate | statusFilter }}</span
              >
              <span
                :style="{ color: buttonColor.itemconfirmed }"
                v-else-if="scope.row.fbillstate === 2"
                >{{ scope.row.fbillstate | statusFilter }}</span
              >
              <span :style="{ color: buttonColor.iteminvalid }" v-else>{{
                scope.row.fbillstate | statusFilter
              }}</span>
            </template>
          </el-table-column>
        </JNPF-table>

        <paginations
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <!-- 主表添加或修改对话框 -->
    <el-dialog
      :fullscreen="true"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      :title="textMap[dialogStatus]"
    >
      <el-tabs type="border-card">
        <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
          <el-row class="JNPF-common-search-box" :gutter="16">
            <el-form @submit.native.prevent label-width="100px" ref="dataForm" :rules="rules" :model="dataForm">
              <el-col :span="8">
                <el-form-item label="单据编号" prop="fbillno">
                  <el-input :disabled="true" v-model="dataForm.fbillno" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item  label="采购日期" prop="forddate">
                  <el-date-picker
                    :disabled="true"
                    v-model="dataForm.forddate"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                 
                  label="预计到货日"
                  prop="fplanrecdate"
                >
                  <el-date-picker v-model="dataForm.fplanrecdate" type="date" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单据状态" prop="fbillstate">
                  <el-select
                    disabled
                    v-model="dataForm.fbillstate"
                    class="filter-item"
                    clearable
                  >
                    <el-option
                      v-for="item in fbillstateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item  label="仓库名称" prop="fstockno">
                  <el-select
                    v-model="dataForm.fstockno"
                    filterable
                    clearable
                    class="filter-item"
                    placeholder="请选择仓库名称"
                  >
                    <el-option
                      v-for="item in fstocknoOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item  label="供应商" prop="fsupno">
                  <el-select
                    v-model="dataForm.fsupno"
                    filterable
                    clearable
                    class="filter-item"
                    placeholder="请选择供应商"
                  >
                    <el-option
                      v-for="item in getListfsupno"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item  label="采购人员" prop="forduser">
                  <el-select
                    style="display: inline-block"
                    clearable
                    filterable
                    v-model="dataForm.forduser"
                    class="filter-item"
                    placeholder="请选择采购人员"
                  >
                    <el-option
                      v-for="item in getListforduser"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  style="width: 97%"
                  class="text"
                  label="备注"
                  prop="fexplanation"
                >
                  <el-input v-model="dataForm.fexplanation" />
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="容器列表">
          <JNPF-table v-loading="listLoading" :data="dataForm.details"  :height="screenHeight-230">
            <el-table-column
              :width="buttonColor.line"
              align="center"
              label="行号"
              prop="fline"
            />
            <el-table-column align="left" label="容器编号" prop="fpackno" width="300">
               <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.fpackno" 
                  v-direction="{ x: 0, y: scope.$index,type:3}"
                >
                  <el-button slot="append" icon="el-icon-search" @click="searchDialogPack(scope.$index)"></el-button>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              :width="buttonColor.name"
              :formatter="fnameFormat"
              align="left"
              label="容器名称"
              prop="fpackname"
            >
            </el-table-column>
            <el-table-column align="left" label="采购价" prop="fbuyprice">
              <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.fbuyprice" 
                  v-direction="{ x: 1, y: scope.$index,type:3}"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量" prop="fqty">
              <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.fqty" 
                  v-direction="{ x: 2, y: scope.$index,type:3}"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column align="left" label="合计" prop="ftotamt">
              <template slot-scope="scope">
                {{scope.row.fqty*scope.row.fbuyprice}}
              </template>
            </el-table-column>
            <el-table-column
              width="160"
              :formatter="datetimeFormat"
              align="left"
              label="生产日期"
              prop="fprocdate"
            >
            <template slot-scope="scope">
               <el-date-picker style="width:130px"  v-model="scope.row.fprocdate" type="date" />
              </template>
            </el-table-column>
            <el-table-column
              width="180"
              align="left"
              label="备注"
              prop="fmemo"
            >
            <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.fmemo" 
                  v-direction="{ x: 4, y: scope.$index,type:3}"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!viewFlag"
              align="left"
              label="操作"
              :width="buttonColor.operationTwo"
              class-name="small-padding"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="handleDelete1(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </JNPF-table>
        </el-tab-pane>
        <el-tab-pane label="容器明细">
          <JNPF-table v-loading="listLoading" :data="dataForm.details2"  :height="screenHeight-230">
            <el-table-column
              :width="buttonColor.line"
              align="center"
              label="行号"
              prop="fline"
            />
            <el-table-column
              width="220"
              align="left"
              label="容器标签"
              prop="frfidbarcode"
            >
                <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.frfidbarcode" 
                  v-direction="{ x: 0, y: scope.$index,type:3}"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              width="220"
              align="left"
              label="容器编号"
              prop="fpackno"
            >
             <template slot-scope="scope">
                  <el-input 
                    v-model="scope.row.fpackno" 
                    v-direction="{ x: 1, y: scope.$index,type:3}"
                  >
                    <el-button slot="append" icon="el-icon-search" @click="searchDialogPack2(scope.$index)"></el-button>
                  </el-input>
                </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="容器名称"
              prop="fpackname"
            >
            </el-table-column>
            <el-table-column
              v-if="!viewFlag"
              align="center"
              label="操作"
              :width="buttonColor.operationTwo"
              class-name="small-padding"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="handleDelete2(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </JNPF-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <div v-if="viewFlag == false">
          <el-button @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" @click="createData"
            >确定</el-button
          >
          <el-button v-else @click="updateData">确定</el-button>
        </div>
        <div v-else>
          <el-button @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" @click="createData"
            >确定</el-button
          >
        </div>
      </span>
    </el-dialog>
    <!-- 容器搜索弹出框 -->
    <packDialog
      :packVisible.sync="packVisible"
      :tableColor="tableColor"
      @packDialog="packDialogValue"
    />
    <packDialog
      :packVisible.sync="packVisible2"
      :tableColor="tableColor"
      @packDialog="packDialogValue2"
    />
    <!-- 人员搜索弹出框 -->
    <userDialog
      :searchVisibleuse.sync="searchVisibleuse"
      :fsiteNo.sync="userDialogFsiteNo"
      :tableColor="tableColor"
      @userDialog="userDialogValue"
    />
  </div>
</template>
<script>
import {
  listrecHead,
  createrecHead,
  updaterecHead,
  deleterecHead,
} from "@/api/tsPackRecHead";
import Pagination from "@/components/Pagination";
import moment from "moment";
import {
  tableColor,
  titleColor,
  exportColor,
  buttonColor,
} from "@/filters/index";
import {
  fsiteOptionsByLevel,
  getListArea,
  getFbillno,
  checkBiz,
  uploadPath2,
} from "@/api/area";
import { getToken } from "@/utils/auth";
import UserDialog from "@/components/UserDialog";
import PackDialog from "@/components/PackDialog";
import { listtsPack } from "@/api/tsPack";
import { getApiUrl } from "@/utils/request";
import QRcode from "@chenfengyuan/vue-qrcode";

const statusMap = {
  1: "待确认",
  2: "已确认",
  8: "已作废",
};

export default {
  name: "STcRecHead",
  components: { Pagination, PackDialog, UserDialog, qrcode: QRcode },
  filters: {
    statusFilter(type) {
      return statusMap[type];
    },
  },
  data() {
    return {
      isAdd1: true,
      isAdd2: true,
      tableindex:0,
       screenHeight: document.body.clientHeight,
      activeName: "first",
      panelHeight: 0,
      downUrl: null,
      uploadVisible: false,
      uploadPath2,
      fstocknoOptions: [],
      buttonColor,
      indexs2: 1,
      packVisible: false,
      packVisible2: false,
      viewFlag: false,
      searchVisibleuse: false,
      userDialogFsiteNo: null,
      userFlag: null,

      getListforduser: null,
      searchVisible: false,
      listLoadingSearch: true,
      totalSearch: 0,
      listQuerySearch: {
        page: 1,
        limit: 20,
        fequipmentno: undefined,
        sort: "create_time",
        order: "desc",
      },
      showAll:false,
      fbuypriceData: 0,
      fqtyData: 1,
      ftotamtData: 0,

      searchListAll: [],
      getListfsupno: [],
      getListfsiteNo: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
        datelist:[new Date(),new Date()],
      listQuery: {
        page: 1,
        limit: 20,
        currentPage:0,
        fstockno: undefined,
        fsiteNo: undefined,
        forduser: undefined,
        forddate: undefined,
        fplanrecdate: undefined,
        frecdate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fsrcbillno: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        sort: "create_time",
        order: "desc",
      },
      fbillstateOptions: [
        { value: 1, label: "待确认" },
        { value: 2, label: "已确认" },
        { value: 8, label: "已作废" },
      ],
      dataForm: {
        fstockno: undefined,
        fsiteNo: undefined,
        forduser: undefined,
        forddate: undefined,
        fplanrecdate: undefined,
        frecdate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fsrcbillno: "0",
        fexplanation: "0",
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        details: [],
        details2: [],
      },
      listTmp: [],
      actionsTmp: [],
      dataForm1: {
        fline: undefined,
        fpackno: undefined,
        fpackname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        fprocdate: undefined,
        ftotamt: undefined,
        fmemo: undefined,
        id: undefined,
      },

      actionsTmp2: [],
      dialogFormVisible3: false,
      dataForm2: {
        fline: undefined,
        fpackno: undefined,
        fpackname: undefined,
        frfidbarcode: undefined,
        id: undefined,
      },

      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rowdata:{},
      dialogStatus: "",
      tableColor,
      titleColor,
      exportColor,
      rules: {
        fstockno: [{ required: true, message: "仓库编号不能为空" }],
        fsiteNo: [{ required: true, message: "客户编号不能为空" }],
        forduser: [{ required: true, message: "采购人员不能为空" }],
        forddate: [{ required: true, message: "采购日期不能为空" }],
        fplanrecdate: [{ required: true, message: "预计到货日不能为空" }],
        fsupno: [{ required: true, message: "供应商编号不能为空" }],
        fbillstate: [
          {
            type: "number",
            message: "单据状态必须为数字值",
            transform: (value) => Number(value),
          },
        ],
      },
      rules1: {
        fline: [
          { required: true, message: "行号不能为空" },
          {
            type: "number",
            message: "行号必须为数字值",
            transform: (value) => Number(value),
          },
        ],
        fpackno: [{ required: true, message: "容器编号不能为空" }],
        fbuyprice: [{ required: true, message: "采购价不能为空" }],
        fqty: [{ required: true, message: "数量不能为空" }],
        ftotamt: [{ required: true, message: "合计不能为空" }],
      },
      rules2: {
        fline: [
          { required: true, message: "行号不能为空" },
          {
            type: "number",
            message: "行号必须为数字值",
            transform: (value) => Number(value),
          },
        ],
        fpackno: [{ required: true, message: "容器编号不能为空" }],
        frfidbarcode: [{ required: true, message: "容器标签不能为空" }],
      },
    };
  },
  watch: {
    fbuypriceData: function (val) {
      if (this.fqtyData && val) {
        const num = (this.fqtyData * parseFloat(val)).toFixed(2);
        return (this.ftotamtData = num);
      } else {
        return (this.ftotamtData = 0);
      }
    },

    fqtyData: function (val) {
      if (this.fqtyData && val) {
        const num = (parseFloat(this.fbuypriceData) * val).toFixed(2);
        return (this.ftotamtData = num);
      } else {
        return (this.ftotamtData = 0);
      }
    },
  },
  created() {
     this.keyCode();
    this.downUrl = getApiUrl() + "xlsx/1-5容器入库.xlsx";
    this.panelHeight = document.documentElement.clientHeight - 350;
    this.alarmdate = [
      this.parserDate(moment(new Date().setDate(1)).format("YYYY-MM-DD")),
      new Date(),
    ];
    this.getList();
    fsiteOptionsByLevel(3)
      .then((response) => {
        this.getListfsiteNo = response.data.data.list;
      })
      .catch(() => {
        this.getListfsiteNo = [];
      });

    this.listQuery.fsiteNo = this.$store.state.user.fsiteNo;
    // 供应商
    getListArea({ flag: 6, arg1: this.$store.state.user.fsiteNo })
      .then((response) => {
        this.getListfsupno = response.data.data.list;
      })
      .catch(() => {
        this.getListfsupno = [];
      });

    // 人员弹出框
    getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
      .then((response) => {
        this.getListforduser = response.data.data.list;
      })
      .catch(() => {
        this.getListforduser = [];
      });
    // 仓库名称
    getListArea({ flag: 30, arg1: this.$store.state.user.fsiteNo })
      .then((response) => {
        this.fstocknoOptions = response.data.data.list;
      })
      .catch(() => {
        this.fstocknoOptions = [];
      });
    // 全部容器列表
    listtsPack({ fsiteNo: this.$store.state.user.fsiteNo, limit: -1 })
      .then((response) => {
        this.searchListAll = response.data.data.list;
      })
      .catch(() => {
        this.searchListAll = [];
      });
  },
  computed: {
    headers() {
      return {
        Authorization: getToken(),
      };
    },
  },
  methods: {
    handleCommand(e){
      if(e=="a")
      {
        this.auditDelete(this.rowdata);
      }
      else
      {
        this.handlePrint(this.rowdata);
      }
    },
    rowclick(data){
      this.rowdata=data;
    },
     //回车
    keyCode() {
      let direction = this.$getDirection();
      let _this=this;
      direction.on("keyup", function (e, val) {
        if (e.keyCode === 13) {
          direction.next();
        }
        if (e.keyCode === 37) {
          direction.previous();
        }
        if (e.keyCode === 38) {
          direction.previousLine();
        }
        if (e.keyCode === 40) {
          direction.nextLine();
        }
        if (e.keyCode == 39) {
          direction.next();
        }
      });
    },
    addrow(){
      this.dataForm.details.push({
        fline:this.dataForm.details.length+1,
        fpackno:"",
        fpackname:'',
        fbuyprice:"",
        ftotamt:'0',
        fprocdate:"",
        fmemo:"",
      })
    },
    addrow2(){
      this.dataForm.details2.push({
         fline:this.dataForm.details2.length+1,
         frfidbarcode:"",
         fpackname:""
      })
    },
    datetimeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD");
    },
    parserDate(date) {
      var t = Date.parse(date);
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, "/")));
      }
    },
    uploadFileSuccess: function (response) {
      this.uploadVisible = false;
      this.$notify.success({
        title: "导入",
        dangerouslyUseHTMLString: true,
        message: response.data,
      });
    },
    handleUpload() {
      this.uploadVisible = true;
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      if (tab.name === "second") {
        // 子表2
        this.handleUpdate2();
        this.resetForm2();
        if (this.dataForm.details2.length > 0) {
          // 计算行号
          let len = this.dataForm.details2.length - 1;
          this.dataForm2.fline = this.dataForm.details2[len].fline + 1;
        } else {
          this.dataForm2.fline = 1;
        }
      } else if (tab.name === "first") {
        // 子表1
        this.activeName = "first";
        this.handleUpdate1();
        this.resetForm1();
        this.fbuypriceData = 0;
        this.fqtyData = 1;
        this.ftotamtData = 0;
        if (this.dataForm.details.length > 0) {
          // 计算行号
          let len = this.dataForm.details.length - 1;
          this.dataForm1.fline = this.dataForm.details[len].fline + 1;
        } else {
          this.dataForm1.fline = 1;
        }
      }
    },
    formatfsiteNo: function (row, column) {
      if (this.getListfsiteNo) {
        for (let i = 0; i < this.getListfsiteNo.length; i++) {
          if (row.fsiteNo === this.getListfsiteNo[i].value) {
            return this.getListfsiteNo[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    // 仓库名称
    formatfstockno: function (row, column) {
      if (this.fstocknoOptions.length > 0) {
        for (let i = 0; i < this.fstocknoOptions.length; i++) {
          if (row.fstockno === this.fstocknoOptions[i].value) {
            return this.fstocknoOptions[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value;
      if (value === "add") {
        this.userDialogFsiteNo = this.dataForm.fsiteNo;
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo;
      }
      this.searchVisibleuse = true;
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      if (this.userFlag === "add") {
        this.dataForm.forduser = value.user.id.toString();
      } else {
        this.listQuery.forduser = value.user.id.toString();
      }
    },

    // 人员
    formatforduser: function (row, column) {
      if (this.getListforduser) {
        for (let i = 0; i < this.getListforduser.length; i++) {
          if (row.forduser == this.getListforduser[i].value) {
            return this.getListforduser[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 容器名称
    fnameFormat: function (row, column) {
      if (this.searchListAll.length > 0) {
        for (let i = 0; i < this.searchListAll.length; i++) {
          if (row.fpackno == this.searchListAll[i].fpackno) {
            return this.searchListAll[i].fpackname;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    searchDialogPack2(id) {
      this.packVisible2 = true;
       this.tableindex=id;
    },

    // 容器弹出框
    packDialogValue2(value) {
      this.dataForm.details2[this.tableindex].fpackno=value.info.fpackno;
       this.dataForm.details2[this.tableindex].fpackname=value.info.fpackname;
      // this.dataForm2.fpackno = value.info.fpackno;
      // this.dataForm2.fpackname = value.info.fpackname;
      // this.fbuypriceData = value.info.fbuyprice;
    },

    // 容器弹出框
    searchDialogPack(id) {
      this.tableindex=id;
      this.packVisible = true;
    },

    // 容器弹出框
    packDialogValue(value) {
      this. dataForm.details[this.tableindex].fpackno= value.info.fpackno;
       this. dataForm.details[this.tableindex].fpackname= value.info.fpackno
      // this.dataForm1.fpackno = value.info.fpackno;
      // this.dataForm1.fpackname = value.info.fpackname;
      // this.fbuypriceData = value.info.fbuyprice;
    },
    // 供应商
    formatfsupno: function (row, column) {
      if (this.getListfsupno.length > 0) {
        for (let i = 0; i < this.getListfsupno.length; i++) {
          if (row.fsupno === this.getListfsupno[i].value) {
            return this.getListfsupno[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    formatDate: function (date) {
      if (typeof date === "object") {
        var ym;
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        if (m < 10) {
          m = "0" + m;
        }
        if (d < 10) {
          d = "0" + d;
        }
        ym = "" + y + m + d;
        return ym;
      } else {
        return date;
      }
    },
    getList() {
      if(this.datelist!=null)
      {
        this.listQuery.ftakedateStart =this.formatDate(this.datelist[0])
        this.listQuery.ftakedateEnd =this.formatDate(this.datelist[0])
      }
      else
      {
        this.listQuery.ftakedateStart =""
        this.listQuery.ftakedateEnd =""
      }
      this.listLoading = true;
      if (this.listQuery.fbillno == "") {
        this.listQuery.fbillno = null;
      }
      listrecHead(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        fstockno: undefined,
        fsiteNo: undefined,
        forduser: undefined,
        forddate: undefined,
        fplanrecdate: undefined,
        frecdate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fsrcbillno: "0",
        fexplanation: "0",
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        details: [],
        details2: [],
      };
    },
    resetForm1() {
      this.dataForm1 = {
        fline: undefined,
        fpackno: undefined,
        fpackname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        fprocdate: undefined,
        ftotamt: undefined,
        fmemo: undefined,
        id: undefined,
      };
    },
    resetForm2() {
      this.dataForm2 = {
        fline: undefined,
        fpackno: undefined,
        fpackname: undefined,
        frfidbarcode: undefined,
        id: undefined,
      };
    },
    handleCreate() {
      this.resetForm();
      this.viewFlag = false;

      // 单据编号
      getFbillno({ flag: 2030 })
        .then((response) => {
          if (response) {
            this.addrow();
            this.addrow2();
            this.dataForm.fbillno = response.data.data;
            this.dialogFormVisible = true;
          }
        })
        .catch(() => {
          this.dataForm.fbillno = "";
        });

      // 供应商
      if (this.getListfsupno.length > 0) {
        this.dataForm.fsupno = this.getListfsupno[0].value;
      }
      // 仓库
      if (this.fstocknoOptions.length > 0) {
        this.dataForm.fstockno = this.fstocknoOptions[0].value;
      }
      this.dataForm.forduser = this.$store.state.user.id.toString();
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;

      this.dataForm.fplanrecdate = new Date();
      this.dataForm.frecdate = new Date();
      this.dataForm.forddate = new Date();
      this.dataForm.fbillstate = 1;
      this.dialogStatus = "create";

      // 子表1
      this.activeName = "first";
      this.handleUpdate1();
      this.resetForm1();
      this.dataForm1.fline = 1;
      this.fbuypriceData = 0;
      this.fqtyData = 1;
      this.ftotamtData = 0;
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id;
          this.dataForm.fupddate = new Date();
          createrecHead(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "添加容器入库主表成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      if (row.fbillstate == "1") {
        this.viewFlag = false;
      } else {
        this.viewFlag = true;
      }
      this.listTmp = row;
      this.actionsTmp = [];
      row.details.forEach((v) => {
        this.actionsTmp.push(v);
      });

      this.actionsTmp2 = [];
      row.details2.forEach((v) => {
        this.actionsTmp2.push(v);
      });

      this.dataForm = Object.assign({}, row);
      this.addrow();
      this.addrow2();
      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      if (row.details.length > 0) {
        var end = row.details[row.details.length - 1];
        this.indexs = end.fline + 1;
      }
      if (row.details2.length > 0) {
        var end2 = row.details2[row.details2.length - 1];
        this.indexs2 = end2.fline + 1;
      }


      // 子表1
      this.activeName = "first";
      this.handleUpdate1();
      this.resetForm1();
      this.fbuypriceData = 0;
      this.fqtyData = 1;
      this.ftotamtData = 0;
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1;
        this.dataForm1.fline = this.dataForm.details[len].fline + 1;
      } else {
        this.dataForm1.fline = 1;
      }
    },
    handlePrint(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogFormVisible3 = true;
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id;
          this.dataForm.fupddate = new Date();
          updaterecHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新容器入库主表成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        }
      });
    },
    audit(row) {
      this.$confirm("是否确定", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dataForm = Object.assign({}, row);
          checkBiz({
            pBillNo: this.dataForm.fbillno,
            pBillState: 2,
            pBizType: "i_pack_rec_head",
            pUser: this.$store.state.user.id,
          })
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  this.dataForm.fbillstate = 2;
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.$notify.success({
                title: "成功",
                message: "确认成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        })
        .catch(() => {});
    },

    auditDelete(row) {
      this.$confirm("是否确定作废", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dataForm = Object.assign({}, row);
          this.dataForm.fbillstate = 8;
          updaterecHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.$notify.success({
                title: "成功",
                message: "作废成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        })
        .catch(() => {});
    },
    handleDelete(row) {
      this.$confirm("是否要删除容器入库主表", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleterecHead(row)
            .then((response) => {
              this.$notify.success({
                title: "成功",
                message: "删除容器入库主表成功",
              });
              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        })
        .catch(() => {});
    },
    indexMethod(index) {
      index = index + 1;
      return index;
    },

    handleUpdate1() {
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },

    // 子表一添加编辑
    handleEdit1(row) {
      this.dataForm1 = Object.assign({}, row);
      this.dataForm1.fpackname = this.fnameFormat(row);
      this.fbuypriceData = row.fbuyprice;
      this.fqtyData = row.fqty;
      this.ftotamtData = row.ftotamt;
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },
    // 子表一编辑保存数据
    editData1() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          if (this.dataForm.details.length > 0) {
            // 子表编辑
            for (const v of this.dataForm.details) {
              if (v.fline === this.dataForm1.fline) {
                const index = this.dataForm.details.indexOf(v);
                this.dataForm1.fbuyprice = this.fbuypriceData;
                this.dataForm1.fqty = this.fqtyData;
                this.dataForm1.ftotamt = this.ftotamtData;
                this.dataForm.details.splice(index, 1, this.dataForm1);
                this.isAdd1 = false;
                break;
              }
            }
            // 子表添加
            if (this.isAdd1) {
              this.dataForm1.fbuyprice = this.fbuypriceData;
              this.dataForm1.fqty = this.fqtyData;
              this.dataForm1.ftotamt = this.ftotamtData;
              this.dataForm.details.push(this.dataForm1);
            }
          } else {
            // 子表第一次添加
            this.dataForm1.fbuyprice = this.fbuypriceData;
            this.dataForm1.fqty = this.fqtyData;
            this.dataForm1.ftotamt = this.ftotamtData;
            this.dataForm.details.push(this.dataForm1);
          }
          this.resetForm1();
          this.isAdd1 = true;
          // 计算行号
          if (this.dataForm.details.length > 0) {
            // 计算行号
            let len = this.dataForm.details.length - 1;
            this.dataForm1.fline = this.dataForm.details[len].fline + 1;
          } else {
            this.dataForm1.fline = 1;
          }
          this.fbuypriceData = 0;
          this.fqtyData = 1;
          this.ftotamtData = 0;
        }
      });
    },

    cancle1() {
      this.resetForm1();
      this.isAdd1 = true;


      // 计算行号
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1;
        this.dataForm1.fline = this.dataForm.details[len].fline + 1;
      } else {
        this.dataForm1.fline = 1;
      }
      this.fbuypriceData = 0;
      this.fqtyData = 1;
      this.ftotamtData = 0;
    },

    handleDelete1(row) {
      const index = this.dataForm.details.indexOf(row);
      this.dataForm.details.splice(index, 1);
      // this.dataForm.details.pop(row)
      this.resetForm1();
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1;
        this.dataForm1.fline = this.dataForm.details[len].fline + 1;
      } else {
        this.dataForm1.fline = 1;
      }
      this.fbuypriceData = 0;
      this.fqtyData = 1;
      this.ftotamtData = 0;
    },
    cancel() {
      this.indexs = 1;
      this.indexs2 = 1;
      this.dialogFormVisible = false;
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.actionsTmp;
          this.dataForm.details2 = this.actionsTmp2;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },
    // 弹窗点击关闭前的回调
    handleClose() {
      this.indexs = 1;
      this.indexs2 = 1;
      this.dialogFormVisible = false;
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.actionsTmp;
          this.dataForm.details2 = this.actionsTmp2;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },

    handleUpdate2() {
      this.dataForm2 = {
        fline: this.indexs2,
        fpackno: undefined,
        fpackname: undefined,
        frfidbarcode: undefined,
        id: undefined,
      };
    },

    handleUpdate1() {
      // 清除验证
    },

    // 子表一添加编辑
    handleEdit2(row) {
      this.dataForm2 = Object.assign({}, row);
      this.dataForm2.fpackname = this.fnameFormat(row);
      // 清除验证
    },
    // 子表一编辑保存数据
    editData2() {
      this.$refs["dataForm2"].validate((valid) => {
        if (valid) {
          if (this.dataForm.details2.length > 0) {
            for (const v of this.dataForm.details2) {
              if (v.fline === this.dataForm2.fline) {
                const index = this.dataForm.details2.indexOf(v);
                this.dataForm.details2.splice(index, 1, this.dataForm2);
                this.isAdd2 = false;
                break;
              }
            }
            if (this.isAdd2) {
              this.dataForm.details2.push(this.dataForm2);
            }
          } else {
            this.dataForm.details2.push(this.dataForm2);
          }
          this.resetForm2();
          this.isAdd2 = true;
          // 清除验证
          if (this.dataForm.details2.length > 0) {
            let len = this.dataForm.details2.length - 1;
            this.dataForm2.fline = this.dataForm.details2[len].fline + 1;
          } else {
            this.dataForm2.fline = 1;
          }
        }
      });
    },

    cancle2() {
      this.resetForm2();
      this.isAdd2 = true;


      // 计算行号
      if (this.dataForm.details2.length > 0) {
        let len = this.dataForm.details2.length - 1;
        this.dataForm2.fline = this.dataForm.details2[len].fline + 1;
      } else {
        this.dataForm2.fline = 1;
      }
    },

    handleDelete2(row) {
      const index = this.dataForm.details2.indexOf(row);
      this.dataForm.details2.splice(index, 1);
      if (this.dataForm.details2.length > 0) {
        let len = this.dataForm.details2.length - 1;
        this.dataForm2.fline = this.dataForm.details2[len].fline + 1;
      } else {
        this.dataForm2.fline = 1;
      }
    },
  },
};
</script>